﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using webapi.Models;
using webapi.Entity;
using System.Data;

namespace webapi.Controllers
{
    public class StudentController : ApiController
    {

      //学生选课
      [HttpGet]
      public IHttpActionResult addSelectCourse(string stu_id, string class_course_id, string time, string selected="")
      {
        //调课时起作用
        if(selected != "") {
          this.deleteSelectCourse(stu_id, selected); 
        } 
        int i = StudentService.addSelectCourse(stu_id, class_course_id, time);
        Boolean msg = i != -1 ? true : false;
        return Json<dynamic>(new { code = 0, msg, i });
      }

      [HttpGet]
      //学生退课
      public IHttpActionResult deleteSelectCourse(string stu_id, string class_course_id)
      {
        int i = StudentService.deleteSelectCourse(stu_id, class_course_id);
        Boolean msg = i != -1 ? true : false;
        return Json<dynamic>(new { code = 0, msg, i });
      }

      //获取开设课程
      [HttpGet]
      public IHttpActionResult getSetUpCourses(string stu_id)
      {
        List<SetUpCourse> courses = this.setCourse(StudentService.getCourseList(), stu_id);
        return Json<dynamic>(new { courses });
      }

      //获取我已选泽的课程
      [HttpGet]
      public IHttpActionResult getMyCourse(string id)
      {
        List<SetUpCourse> courses = this.setCourse(StudentService.getOwnCourse(id), id);
        return Json<dynamic>(new { courses });
      }

      //根据课程号获取开设的班级
      public IHttpActionResult getCourseClassById(string id, string stu_id)
      {
        List<SetUpCourse> courses = this.setCourse(StudentService.getCourseById(id), stu_id);
        return Json<dynamic>(new { courses });
      }

      //填充数据
      protected List<SetUpCourse> setCourse(DataRowCollection dr, string id)
      {
        List<SetUpCourse> courses = new List<SetUpCourse>();
        int len = dr.Count;
        string class_course_id;
        for (int i = 0; i < len; i++)
        {
          class_course_id = dr[i][2].ToString().Trim();
          courses.Add(new SetUpCourse()
          {
            name = dr[i][0].ToString().Trim(),
            course_id = dr[i][1].ToString().Trim(),
            class_course_id = class_course_id,
            point = (double)dr[i][3],
            day = (int)dr[i][4],
            time = (int)dr[i][5],
            start = (int)dr[i][6],
            last = (int)dr[i][7],
            count = int.Parse("0" + dr[i][8]),
            choose = SetUpCourseService.getSelectCountById(class_course_id),
            isSelect = StudentService.isSelectCourse(class_course_id, id)
          });
        }
        return courses;
      }
    }
}
